package com.gjintel.business.website.controller;

import java.util.Date;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.business.webcontent.service.IWebContentService;
import com.gjintel.business.webtypemanage.model.WebTypeInfo;
import com.gjintel.business.webtypemanage.service.IWebTypeManageService;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.DateJsonValueProcessor;

import com.gjintel.sdk.util.StringUtil;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;


/**
 * @description 网站首页 
 * @author wwang 
 * @date 2016年9月20日
 */
@SuppressWarnings("all")
@Controller
@RequestMapping("/web")
public class WebController {
	
	@Resource
	private IWebContentService webContentService;
	
	@Autowired
	private IWebTypeManageService webTypeManageService;
	
	/**
	 * @description 包河区公共资源交易网网站首页
	 * @author wwang 
	 * @date 2016年9月22日
	 * @return
	 */
	@RequestMapping("/home")
	public ModelAndView home(){
		ModelAndView mv=new ModelAndView("/website/homepage/home");
		DataSet dataSet = this.webContentService.get(DataSet.class, Constant.DATASET_ID);
		mv.addObject("dataSet", dataSet);
		return mv;
	}
	
	/**
	 * @description 新闻主页
	 * @author wwang 
	 * @date 2016年9月22日
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(){
		ModelAndView mv=new ModelAndView("/website/index");
		return mv;
	}
	
	/**
	 * @description 新闻列表页面 
	 * @author wwang 
	 * @date 2016年9月22日
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(String webTypeId){
		ModelAndView mv=new ModelAndView("/website/list");
		mv.addObject("webTypeId", webTypeId);
		return mv;
	}
	
	/**
	 * @description 获得新闻类型列表数据
	 * @author wwang
	 * @date 2016-4-6 下午03:37:05
	 * @param contentTypeId
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/contentLists")
	@ResponseBody
	public JSONObject contentLists(Page page, WebContent webcontent) {
		ModelAndView mv = new ModelAndView("/web/web-news-list");
		Sort sort=new Sort();
		sort.setFields("createTime");
		sort.setOrders("desc");
		this.webContentService.findAllJoinProject(page, webcontent);
		
		return CommUtil.getPageJSONData(page, true);
	}
	
	
	/**
	 * @description 获取站点信息dataset 
	 * @author wwang 
	 * @date 2016年9月21日
	 * @return
	 */
	@RequestMapping("/getDataset")
	@ResponseBody
	public String getDataset() {
		DataSet dataset = this.webContentService.get(DataSet.class, Constant.DATASET_ID);
		return JSONObject.fromObject(dataset).toString();
	}
	
	/**
	 * @description 获取新闻类型
	 * @author wwang 
	 * @date 2016年9月21日
	 * @return
	 */
	@RequestMapping("/getWebTypeList")
	@ResponseBody
	public String getWebTypeList() {
		List<WebTypeInfo> webTypeList = this.webTypeManageService.findAll();
		return JSONArray.fromObject(webTypeList).toString();
	}
	
	/**
	 * @description根据id查询新闻类型信息 
	 * @author wwang 
	 * @date 2016年9月22日
	 * @param id
	 * @return
	 */
	@RequestMapping("/getWebType")
	@ResponseBody
	public String getWebType(String id) {
		WebTypeInfo webType = this.webTypeManageService.get(WebTypeInfo.class,id);
		return JSONObject.fromObject(webType).toString();
	}

	
	/**
	 * @description 进入登录页面
	 * @author shy
	 * @date 2016-9-20
	 * @return
	 */
	@RequestMapping("/login")
	public ModelAndView login(){
		ModelAndView mv =new ModelAndView("/login/login-ca");
		return mv;
	}
	
	/**
	 * @description 进入注册页面
	 * @author shy
	 * @date 2016-9-20
	 * @return
	 */
	@RequestMapping("/register")
	public ModelAndView register(){
		ModelAndView mv =new ModelAndView("/register/register-input");
		return mv;
	}
	
	/**
	 * @description 获取公告模块数据（自动生成）
	 * @author shy
	 * @date 2016-9-22 
	 * @param contentTypeId
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/getAutoNotice")
	@ResponseBody
	public JSONArray getAutoNotice(Page page,WebContent webcontent) {
		page.setPageNo(1);
		this.webContentService.findAllJoinProject(page, webcontent);
		List<WebContent> list = page.getResult();
		DateJsonValueProcessor processor = new DateJsonValueProcessor();
		DateJsonValueProcessor dateProcessor = new DateJsonValueProcessor("yyyy-MM-dd");
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, processor);
		config.registerJsonValueProcessor(java.sql.Date.class, dateProcessor);
		return JSONArray.fromObject(list,config);
	}
	
	/**
	 * @description 获取公告模块数据（手动录入的）
	 * @author shy
	 * @date 2016-9-22 
	 * @param contentTypeId
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/getUnAutoNotice")
	@ResponseBody
	public JSONArray getUnAutoNotice(String type) {
		List<WebContent> list = this.webContentService.getUnAutoNotice(type);
		DateJsonValueProcessor processor = new DateJsonValueProcessor();
		DateJsonValueProcessor dateProcessor = new DateJsonValueProcessor("yyyy-MM-dd");
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, processor);
		config.registerJsonValueProcessor(java.sql.Date.class, dateProcessor);
		return JSONArray.fromObject(list,config);
	}

	/**
	 * @description 网站新闻详情 
	 * @author wwang 
	 * @date 2016年9月29日
	 * @param id
	 * @return
	 */
	@RequestMapping("/getWebDetail")
	public ModelAndView getWebDetail(String id) {
		ModelAndView mv = new ModelAndView("/website/web-detail");
		if (!StringUtil.isEmpty(id)) {
			List<WebContent> webList = webContentService.findAll(id);
			WebContent webcontent = null;
			if(webList!=null&&webList.size()>0){
				webcontent=webContentService.findAll(id).get(0);
			}
			List<Resources> resLlist = FileResUtil.findResources(id);//附件
			mv.addObject("webcontent", webcontent);
			mv.addObject("resLlist", resLlist);
		}
		return mv;
	}
	
	/**
	 * @description 新闻搜索列表页面 
	 * @author wwang 
	 * @date 2016年9月22日
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/searchList")
	public ModelAndView searchList(String title) throws Exception{
		ModelAndView mv=new ModelAndView("/website/search-list");
		mv.addObject("title", new String(title.getBytes("iso8859-1"),"utf-8"));
		return mv;
	}
	
	/**
	 * @description 下载查看文件 
	 * @author wei 
	 * @date 2016-8-16
	 * @param resId
	 * @param response
	 * @param request
	 */
	@RequestMapping("/fileView")
	public void fileView(String resId, HttpServletResponse response, HttpServletRequest request) {
		Resources resource = this.webContentService.get(Resources.class, resId);
		OutputStream os = null;
		try {
			if (resource == null) {
				PrintWriter out = response.getWriter();
				response.setHeader("Content-Disposition", "attachment;");
				response.addHeader("Pargam", "no-cache");
				response.addHeader("Cache-Control", "no-cache");
				out.write("找不到对应的文件数据！");
				out.flush();
			} else {
				String fileRealPath = resource.getFilePath() + File.separator + resource.getId() + resource.getExeName();
				String filePath = request.getSession().getServletContext().getRealPath("/");
				fileRealPath = filePath + "file_resource" + fileRealPath;
				String fileName = resource.getOldName();
				os = response.getOutputStream();
				processDownload(fileRealPath, fileName, request, response);
//				String Agent = request.getHeader("User-Agent");

//				Agent = Agent.toLowerCase();
//				if (Agent.indexOf("firefox") != -1) {
//					fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
//				} else if (Agent.indexOf("msie") != -1) {
//					fileName = java.net.URLEncoder.encode(fileName, "utf-8");
//				} else {
//					fileName = java.net.URLEncoder.encode(fileName, "utf-8");
//				}
//				response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//				response.setContentType("application/octet-stream; charset=utf-8");
//
//				Agent = Agent.toLowerCase();
//				if (Agent.indexOf("firefox") != -1) {
//					fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
//				} else if (Agent.indexOf("msie") != -1) {
//					fileName = java.net.URLEncoder.encode(fileName, "utf-8");
//				} else {
//					fileName = java.net.URLEncoder.encode(fileName, "utf-8");
//				}
//				response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//				response.setContentType("application/octet-stream; charset=utf-8");
//
//				response.addHeader("Pargam", "no-cache");
//				response.addHeader("Cache-Control", "no-cache");
//				FileInputStream fis = new FileInputStream(new File(fileRealPath));
//				byte[] buff = new byte[1024];
//				int index = 0;
//				while ((index = fis.read(buff)) != -1) {
//					os.write(buff, 0, index);
//				}
//				os.flush();
			}
		} catch (Exception e) {
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param fileName
	 * @param saveName
	 * @param request
	 * @param response
	 * @return
	 */
	private boolean processDownload(String path, String saveName, HttpServletRequest request, HttpServletResponse response) {
		boolean success = true;
		// 获取文件下载所在的路径
		//String path = request.getServletContext().getRealPath("/upload");
		File fileLoad = new File(path); // 下载文件
		long fileLength = fileLoad.length(); // 文件大小
		byte[] buffer = new byte[1024]; // 缓冲字节数组
		try {
			response.reset();
			response.setHeader("Content-disposition", "attachment;filename=\""
					+ new String(saveName.getBytes("gb2312"), "ISO-8859-1")
					+ "\"");
			response.setContentType("application/octet-stream");
			response.setHeader("Content_Length", String.valueOf(fileLength));

			OutputStream os = response.getOutputStream();
			FileInputStream in = new FileInputStream(fileLoad);
			int hasRead = 0;
			while ((hasRead = in.read(buffer)) != -1) {
				os.write(buffer, 0, hasRead);
			}
			os.flush();
			os.close();
			in.close();
		} catch (IOException e) {
			success = false;
			e.printStackTrace();
		}
		return success;
	}
}
